#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>

int main()
{
    int pipe1[2], pipe2[2];
    pipe(pipe1);
    pipe(pipe2);

    pid_t pid1 = fork();
    char* args_ls[] = {"ls", "-l", NULL};
    if(pid1 == 0)
    {
        dup2(pipe1[1], STDOUT_FILENO);
        close(pipe1[0]);
        close(pipe1[1]);
        close(pipe2[0]);
        close(pipe2[1]);
        execvp(args_ls[0], args_ls);
    }

    pid_t pid2 = fork();
    char* args_grep[] = {"grep", "txt", NULL};
    if(pid2 == 0)
    {
        dup2(pipe1[0], STDIN_FILENO);
        dup2(pipe2[1], STDOUT_FILENO);
        close(pipe1[0]);
        close(pipe1[1]);
        close(pipe2[0]);
        close(pipe2[1]);  
        execvp(args_grep[0], args_grep);
    }

    close(pipe1[0]);
    close(pipe1[1]);
    close(pipe2[1]); 

    int fd = open("result.txt",  O_WRONLY | O_CREAT | O_TRUNC, 0644);
    dup2(fd, STDOUT_FILENO);
    char buf[1024];
    int n;
    while((n = read(pipe2[0], buf, sizeof(buf))) > 0)
    {
        write(STDOUT_FILENO, buf, n);
    }

    close(pipe2[0]);
    close(fd);
    wait(NULL);
    wait(NULL);

    return 0;
}
